<template>
    <n-space>
        <n-button type="info" @click="insertArea" style="margin-bottom: 5px">新增</n-button>
        <n-button type="tertiary" @click="refreshTree" style="margin-bottom: 5px">刷新</n-button>
        <n-button type="success" :loading="printLoading" @click="batchGenCode(printDoms)" style="margin-bottom: 5px">批量生成二维码</n-button>
    </n-space>
    <n-data-table
        :loading="loading"
        default-expand-all
        :columns="columns"
        :data="data"
        :row-key="rowKey"
    />
    <n-modal
        preset="dialog"
        :show-icon="false"
        :title="modal.title"
        style="width: 50%"
        positive-text="确定"
        negative-text="取消"
        @positive-click="clickOk"
        @negative-click="clickCancel"
        v-model:show="modal.show">
        <div ref="printDom" style="display: flex;align-items: center;flex-direction: column;height: 100%" v-if="modal.showImg">
            <n-image style="margin-top: 10%" :src="modal.imgUrl" />
            <p style="font-size: 24px;color: #D31FB1">爽爽的贵阳(<em style="font-size: 25px;color: #FFBB00">社区心愿</em>)</p>
            <p style="margin-top: 2%;font-size: 28px;color: #FF4A25">{{ modal.title }}</p>
        </div>
        <n-button v-if="modal.showImg" @click="printThisWindow(printDom)">打印</n-button>
        <n-form
            v-else
            ref="formRef"
            :label-width="80"
            :model="form"
            :rules="rules"
            size="medium">
            <n-form-item label="上级社区" path="parentCode">
                <n-tree-select
                    placeholder="请选择"
                    :options="data"
                    :default-value="form.parentCode"
                    @update:value="handleUpdateValue"
                />
            </n-form-item>
            <n-form-item label="名称" path="name">
                <n-input v-model:value="form.name" placeholder="请输入" clearable />
            </n-form-item>
            <n-form-item label="社区代码" path="areaCode">
                <n-input v-model:value="form.areaCode" placeholder="请输入" clearable />
            </n-form-item>
            <n-form-item label="简称" path="shortName">
                <n-input v-model:value="form.shortName" placeholder="请输入" clearable />
            </n-form-item>
        </n-form>
    </n-modal>
    <n-modal
        preset="dialog"
        :show-icon="false"
        style="width: 45%"
        positive-text="打印"
        negative-text="取消"
        @positive-click="clickPrint(printDoms)"
        @negative-click="clickPrintCancel"
        v-model:show="printMadel.show">
        <!-- 页面展示不能过高。当前页面展示即可 -->
        <n-scrollbar style="max-height: 650px">
            <!-- 打印部分 -->
            <div ref="printDoms">
                <!-- a4纸的宽高595,842 -->
                <div v-for="item in printMadel.imgs" style="display: flex;align-items: center;flex-direction: column;height: 1148px;">
                    <img :src="item.image" style="margin-top: 30%;width: 280px" alt="">
                    <p style="font-size: 24px;color: #D31FB1">爽爽的贵阳(<em style="font-size: 25px;color: #FFBB00">社区心愿</em>)</p>
                    <p style="font-size: 28px;color: #FF4A25">{{ item.shortName || item.name }}</p>
                </div>
            </div>
        </n-scrollbar>
    </n-modal>
</template>
<script lang="ts">
import {defineComponent, onMounted, ref, reactive} from 'vue'
import {columnsInfo, formInfo, rulesInfo, RowData} from './types';
import {areaTree, insert, update, deleteById, genQrCode, batchGenQrCode} from "@/api/area";
import {DataTableColumns, FormInst, NButton, NDropdown} from "naive-ui";
import {outPutPdf} from "@/utils/print";

export default defineComponent({
    setup() {
        const modal = reactive({
            show: false,
            title: `新增`,
            showImg: false,
            imgUrl: ``,
        });
        const printMadel = reactive({
            show: false,
            imgs: [],
        });
        const printLoading = ref(false);
        const form = reactive(formInfo);
        const rules = ref(rulesInfo);
        const columnsActions: DataTableColumns<RowData> = [
            {
                title: '操作',
                key: 'actions',
                render: (row: RowData) => {
                    return h(NDropdown, {
                        options: [
                            {
                                label: `编辑`,
                                key: 'edit',
                                props: {
                                    onClick: () => {
                                        modal.show = true;
                                        modal.showImg = false;
                                        modal.title = `编辑`;
                                        form.id = row.id;
                                        form.name = row.name;
                                        form.areaCode = row.areaCode;
                                        form.parentCode = row.parentCode;
                                        form.shortName = row.shortName;
                                    }
                                }
                            },
                            {
                                label: `删除`,
                                key: 'delete',
                                props: {
                                    onClick: () => {
                                        window.$dialog.warning({
                                            title: '警告',
                                            content: `是否删除该项数据？`,
                                            positiveText: '确定',
                                            negativeText: '取消',
                                            onPositiveClick: () => {
                                                deleteById(row.id).then(({code, message}: any) => {
                                                    if (code === 200) {
                                                        loadData();
                                                    } else {
                                                        window.$message.error(message);
                                                    }
                                                });
                                            },
                                        });
                                    }
                                }
                            },
                            {
                                label: `生成二维码`,
                                key: 'g-code',
                                disabled: (row.children || []).length > 0,
                                props: {
                                    onClick: () => {
                                        genQrCode({url: `${import.meta.env.VITE_APP_QCODE_URL}?areaCode=${row.areaCode}`}).then(({ data }: any) => {
                                            modal.imgUrl = data;
                                            modal.showImg = true;
                                            modal.title = row.shortName || row.name;
                                            modal.show = true;
                                        });
                                    }
                                }
                            },
                        ]
                    }, {default: () => h(NButton, {size: 'small',}, {default: () => '更多↓'})})
                }
            }
        ];

        const columns = ref(columnsInfo.concat(columnsActions));
        const formRef = ref<FormInst | null>(null);
        const data = ref<RowData[]>([]);
        const loading = ref(false);
        const areaOptions = ref<any[]>([]);
        const printDom = ref(null);
        const printDoms = ref<HTMLElement | null>(null);
        onMounted(() => {
            refreshTree();
        });

        const refreshTree = () => {
            loadData().then((res) => {
                data.value = res;
                areaOptions.value = getOptions(res);
            });
        }

        /**
         * 获取社区下拉树
         */
        const getOptions = (data: RowData[]) => {
            if (data) {
                return data.filter((item: any) => {
                    item.label = item.shortName || item.name;
                    item.key = item.areaCode;
                    if (item.children && item.children.length) {
                        getOptions(item.children);
                    } else {
                        delete item.children;
                    }
                    return true;
                });
            }
            return [];
        }

        /**
         * 加载表格数据
         */
        const loadData = async () => {
            loading.value = true;
            const {data} = await areaTree({city: '520100'});
            loading.value = false;
            return data
        }

        /**
         * 点击新增
         */
        const insertArea = () => {
            modal.show = true;
            modal.showImg = false;
            modal.title = `新增`;
            form.name = ``;
            form.id = 0;
            form.areaCode = ``;
            form.parentCode = ``;
            form.shortName = ``;
        }

        /**
         * 点击对话框确定
         */
        const clickOk = async () => {
            const valid = await formRef.value?.validate();
            if (!valid) {
                if (!form.id) {
                    const {code, message}: any = await insert(form);
                    if (code === 200) {
                        window.$message.success(message);
                    }
                } else {
                    const {code, message}: any = await update(form);
                    if (code === 200) {
                        window.$message.success(message);
                    }
                }
                modal.show = false;
                refreshTree();
            }
        }

        /**
         * 取消关闭
         */
        const clickCancel = () => {
            modal.show = false;
        }

        /**
         * 选择社区树
         * @param value 选中的值
         * @param option 选中项全部数据
         */
        const handleUpdateValue = (value: string, option: any) => {
            form.parentCode = value;
        }

        const printThisWindow = (dom: HTMLElement) => {
            outPutPdf(dom, '社区二维码', false, true, () => {});
        }

        /**
         * 批量生成二维码
         */
        const batchGenCode = () => {
            batchGenQrCode({url: `${import.meta.env.VITE_APP_QCODE_URL}?areaCode=`}).then(({data}: any) => {
                printMadel.show = true;
                printMadel.imgs = data;
            });
        }

        /**
         * 批量生成二维码
         * @param dom
         */
        const clickPrint = (dom: HTMLElement) => {
            outPutPdf(dom, '社区二维码', false, true, () => {});
        }

        /**
         * 批量生成二维码
         * @param dom
         */
        const clickPrintCancel = () => {
            printMadel.show = false;
            printMadel.imgs = [];
        }

        return {
            rowKey: (row: RowData) => row.id,
            columns,
            loading,
            modal,
            data,
            form,
            rules,
            clickOk,
            clickCancel,
            loadData,
            insertArea,
            handleUpdateValue,
            refreshTree,
            printThisWindow,
            printDom,
            printDoms,
            batchGenCode,
            printLoading,
            printMadel,
            clickPrint,
            clickPrintCancel,
        }
    }
})
</script>
<style lang="scss" scoped>
</style>
